#!/usr/bin/env node

/**
 * 代币信息查询和交易准备脚本
 * 查询代币信息并准备交易数据，不执行真实交易
 */

const axios = require('axios');
const {
  Connection,
  PublicKey,
  LAMPORTS_PER_SOL,
} = require('@solana/web3.js');
const {
  getAssociatedTokenAddress,
  getAccount,
} = require('@solana/spl-token');

// 配置
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:7172';
const DEVNET_RPC = 'https://api.devnet.solana.com';

// 代币信息
const TOKEN_MINT = '6bMwTwA65tumXUquh4ZGxYxmPyy57szPqcPHdjd2qTj1';
const YOUR_ADDRESS = 'shTdKtBScJMC4GkKmasiE9iMKrtZnMFUtwVTdSXsKac';

async function queryTokenInfo() {
  console.log('🔍 查询代币详细信息');
  console.log('='.repeat(50));
  
  const connection = new Connection(DEVNET_RPC, 'confirmed');
  
  try {
    // 1. 查询代币基本信息
    console.log('\n1️⃣ 代币基本信息:');
    console.log(`📍 代币地址: ${TOKEN_MINT}`);
    
    // 查询代币供应量
    const mintInfo = await connection.getParsedAccountInfo(new PublicKey(TOKEN_MINT));
    if (mintInfo.value && mintInfo.value.data.parsed) {
      const { decimals, supply } = mintInfo.value.data.parsed.info;
      console.log(`🔢 小数位数: ${decimals}`);
      console.log(`💰 总供应量: ${supply}`);
      console.log(`📊 格式化供应量: ${(Number(supply) / Math.pow(10, decimals)).toLocaleString()}`);
    }
    
    // 2. 查询您的账户信息
    console.log('\n2️⃣ 您的账户信息:');
    console.log(`👤 您的地址: ${YOUR_ADDRESS}`);
    
    const yourPublicKey = new PublicKey(YOUR_ADDRESS);
    const balance = await connection.getBalance(yourPublicKey);
    const solBalance = balance / LAMPORTS_PER_SOL;
    
    console.log(`💵 SOL 余额: ${solBalance.toFixed(6)} SOL`);
    
    // 3. 查询您的代币账户
    console.log('\n3️⃣ 您的代币持有情况:');
    try {
      const tokenAccount = await getAssociatedTokenAddress(
        new PublicKey(TOKEN_MINT), 
        yourPublicKey
      );
      console.log(`📍 代币账户地址: ${tokenAccount.toString()}`);
      
      const account = await getAccount(connection, tokenAccount);
      const tokenBalance = Number(account.amount) / Math.pow(10, 9); // 假设9位小数
      
      console.log(`🪙 代币余额: ${tokenBalance.toLocaleString()} 个代币`);
      console.log(`📊 原始余额: ${account.amount.toString()}`);
      
    } catch (error) {
      console.log(`ℹ️ 您还没有持有此代币`);
      console.log(`ℹ️ 或者代币账户尚未创建`);
    }
    
    // 4. 查询代币的最近交易
    console.log('\n4️⃣ 代币最近交易:');
    try {
      const signatures = await connection.getSignaturesForAddress(
        new PublicKey(TOKEN_MINT),
        { limit: 5 }
      );
      
      if (signatures.length > 0) {
        console.log(`📈 找到 ${signatures.length} 笔最近交易:`);
        signatures.forEach((sig, index) => {
          console.log(`${index + 1}. ${sig.signature}`);
          console.log(`   时间: ${new Date(sig.blockTime * 1000).toLocaleString()}`);
          console.log(`   Solscan: https://solscan.io/tx/${sig.signature}?cluster=devnet`);
        });
      } else {
        console.log(`ℹ️ 暂无交易记录`);
      }
    } catch (error) {
      console.log(`⚠️ 查询交易记录失败: ${error.message}`);
    }
    
    // 5. 从API查询代币信息
    console.log('\n5️⃣ API代币信息:');
    try {
      const response = await axios.get(`${API_URL}/api/tokens?mint=${TOKEN_MINT}`);
      if (response.data.success && response.data.tokens.length > 0) {
        const token = response.data.tokens[0];
        console.log(`✅ API数据获取成功:`);
        console.log(`- 名称: ${token.name}`);
        console.log(`- 符号: ${token.symbol}`);
        console.log(`- 描述: ${token.description}`);
        console.log(`- 创建者: ${token.creator}`);
        console.log(`- 创建时间: ${token.createdAt}`);
      } else {
        console.log(`⚠️ API中未找到代币信息`);
      }
    } catch (error) {
      console.log(`⚠️ API查询失败: ${error.message}`);
    }
    
    // 6. 生成交易链接
    console.log('\n6️⃣ 区块链浏览器链接:');
    console.log(`🔗 代币页面:`);
    console.log(`   Solscan: https://solscan.io/token/${TOKEN_MINT}?cluster=devnet`);
    console.log(`   Solana Explorer: https://explorer.solana.com/address/${TOKEN_MINT}?cluster=devnet`);
    
    console.log(`🔗 您的账户页面:`);
    console.log(`   Solscan: https://solscan.io/account/${YOUR_ADDRESS}?cluster=devnet`);
    console.log(`   Solana Explorer: https://explorer.solana.com/address/${YOUR_ADDRESS}?cluster=devnet`);
    
    // 7. 交易建议
    console.log('\n7️⃣ 交易建议:');
    if (solBalance < 0.1) {
      console.log(`⚠️ 建议先获取一些devnet SOL用于测试`);
      console.log(`💧 Devnet水龙头: https://faucet.solana.com/`);
    } else {
      console.log(`✅ SOL余额充足，可以进行交易测试`);
    }
    
    console.log(`\n📝 要执行真实交易测试:`);
    console.log(`1. 确保您有足够的SOL余额`);
    console.log(`2. 创建包含私钥的buyer-wallet.json文件`);
    console.log(`3. 运行: node scripts/real-trade-test.js --confirm`);
    
    console.log(`\n🎯 要继续模拟交易测试:`);
    console.log(`运行: node scripts/trade-test.js`);
    
  } catch (error) {
    console.error('❌ 查询过程中发生错误:', error.message);
  }
}

// 运行查询
console.log(`🚀 代币信息查询工具`);
console.log(`代币: ${TOKEN_MINT}`);
console.log(`地址: ${YOUR_ADDRESS}`);

queryTokenInfo();
